package com.ruoyi.controller.jpjs.excellence;

import com.ruoyi.common.config.Global;
import com.ruoyi.common.config.ServerConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.domain.jpjs.common.excellence.Excellence;
import com.ruoyi.domain.jpjs.common.excellence.ExcellenceParam;
import com.ruoyi.domain.jpjs.common.excellence.ExcellenctDetail;
import com.ruoyi.framework.util.ShiroUtils;
import com.ruoyi.service.jpjs.excellence.ExcellenceService;
import com.ruoyi.system.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author C.fw
 * @explain 危大工程控制层
 * @since 2020/8/15 15:43
 */
@Controller
@RequestMapping("/excellenceMonitor")
public class ExcellenceController extends BaseController {

    private String prefix = "jpjs/excellence";

    @Autowired
    private ExcellenceService excellenceService;

    /**
     * 危大工程页面
     */
    @GetMapping()
    public String View() {
        return prefix + "/excellenceMonitor";
    }

    /**
     * 危大工程页面: 获取列表数据
     */
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo selectExcellenceList(@RequestParam Map<String, Object> map) {
        startPage();
        map.put("programName", map.get("programName").toString().trim().replaceAll(",", ""));
        // 获取当前登录人对应的项目权限
        getUserId(map);
        List<Excellence> list = excellenceService.getExcellenceList(map);
        return getDataTable(list);
    }

    private void getUserId(@RequestParam Map<String, Object> map) {
        // 获取当前登录人对应的项目权限
        // 获取当前的用户信息
        SysUser currentUser = ShiroUtils.getSysUser();
        // 获取当前的用户ID
        Long userId = currentUser.getUserId();
        map.put("userId", userId);
    }

    /**
     * 危大工程新增页面
     */
    @GetMapping("/add")
    public String addView(ModelMap mmp, String programName, String companyId, String proId) {
        Map<String, Object> map = new HashMap<>();
        map.put("companyId", companyId);
        map.put("proId", proId);
        mmp.put("companyId", companyId);
        mmp.put("programId", proId);
        mmp.put("programName", programName);
        return prefix + "/excellenceAdd";
    }

    /**
     * 危大工程新增页面:保存
     */
    @PostMapping("/save")
    @ResponseBody
    public AjaxResult save(ExcellenceParam excellenceParam) {
        List<Excellence> excellenceList = excellenceParam.getExcellence();

        // 获取当前的用户信息
        SysUser currentUser = ShiroUtils.getSysUser();
        String userName = currentUser.getUserName();
        for (Excellence excellence : excellenceList) {
            excellence.setCompanyId(excellenceParam.getCompanyId());
            excellence.setProgramId(excellenceParam.getProgramId());
            excellence.setUpdateBy(userName);
        }
        return toAjax(excellenceService.insertExcellenceBatches(excellenceList));
    }

    /**
     * 危大工程编辑页面
     */
    @GetMapping("/editView")
    public String editListView(ModelMap mmp, String excellenceId) {
        mmp.put("excellenceId", excellenceId);
        return prefix + "/excellenceEdit";
    }

    /**
     * 危大工程编辑页面:保存
     */
    @PostMapping("/update")
    @ResponseBody
    public AjaxResult update(ExcellenceParam excellenceParam) {
        List<Excellence> excellenceList = excellenceParam.getExcellence();
        Excellence excellence = excellenceList.get(0);
        excellence.setExcellenceId(excellenceParam.getExcellenceId());
        SysUser currentUser = ShiroUtils.getSysUser();
        excellence.setUpdateBy(currentUser.getUserName());
        return toAjax(excellenceService.updateExcellenceInfo(excellence));
    }

    /**
     * 危大工程页面:删除
     */
    @PostMapping("/remove")
    @ResponseBody
    public AjaxResult remove(String ids) {
        try {
            return toAjax(excellenceService.deleteExcellenceById(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 危大工程页面:导出
     */
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(@RequestParam Map<String, Object> map) {
        // Step1 获取需要导出的数据
        List<Excellence> list = excellenceService.getExcellenceList(map);
        ExcelUtil<Excellence> util = new ExcelUtil<Excellence>(Excellence.class);
        return util.exportExcel(list, "创优创标");
    }

    /**
     * 危大工程页面:跳转动态管理详情页面
     */
    @GetMapping("/detail/{excellenceId}")
    public String detail(@PathVariable("excellenceId") Long excellenceId, ModelMap mmap) {
        mmap.put("excellenceId", excellenceId);
        return prefix + "/excellenceDetail";
    }

    /**
     * 动态管理详情页面:获取数据列表
     */
    @PostMapping("/selectExcellenceList")
    @ResponseBody
    public TableDataInfo selectExcellenceList(Excellence excellence) {
        startPage();
        Map<String, Object> map = new HashMap<>();
        map.put("excellenceId", excellence.getExcellenceId());
        List<ExcellenctDetail> list = excellenceService.selectExcellenceDetailList(map);
        return getDataTable(list);
    }

    /**
     * 动态详情页面:To新增页面
     */
    @GetMapping("/detailAdd/{excellenceId}")
    public String detailAdd(@PathVariable("excellenceId") Long excellenceId, ModelMap mmap) {
        mmap.put("excellenceId", excellenceId);
        return prefix + "/excellenceDetailAdd";
    }

    /**
     * 新增页面:新增详情
     */
    @PostMapping("/upload")
    @ResponseBody
    public AjaxResult updateAvatar(@RequestParam("file") MultipartFile file, ExcellenctDetail excellenctDetail) {
        try {

            // Step1 物理上传
            String fileName = FileUploadUtils.upload(Global.getUploadPath(), file);

            // Step1.2 准备参数
            excellenctDetail.setPhysicalPath(getPhysicalPath(Global.getUploadPath(), fileName));
            excellenctDetail.setFileName(fileName);
            excellenctDetail.setFilePath(ServerConfig.getUrl() + fileName);

            // Step2 更新响应
            return toAjax(excellenceService.insertExcellenceDetail(excellenctDetail));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    private String getPhysicalPath(String filePath, String fileName) {
        String replace = fileName.replace("/profile/upload", "");
        String physicalPath = filePath + replace;
        return physicalPath;
    }

    /**
     * 动态详情页面:删除
     */
    @PostMapping("/removeDetail")
    @ResponseBody
    public AjaxResult removeDetail(String ids) {
        try {
            return toAjax(excellenceService.deleteDetailById(ids));
        } catch (Exception e) {
            return error(e.getMessage());
        }
    }

    /**
     * 动态详情页面:导出
     */
    @PostMapping("/exportDetail")
    @ResponseBody
    public AjaxResult exportDetail(@RequestParam Map<String, Object> map) {
        // Step1 获取需要导出的数据
        List<ExcellenctDetail> list = excellenceService.selectExcellenceDetailList(map);
        ExcelUtil<ExcellenctDetail> util = new ExcelUtil<ExcellenctDetail>(ExcellenctDetail.class);
        return util.exportExcel(list, "创优创标每月管理动态");
    }

    /**
     * 详情页面 编辑页面
     */
    @GetMapping("/detailEditView/{excellenceId}")
    public String detailEditView(@PathVariable("excellenceId") Long excellenceId, ModelMap mmap) {
        mmap.put("excellenceId", excellenceId);
        HashMap<String, Object> map = new HashMap<>();
        map.put("excellenceId", excellenceId);
        mmap.put("excellence", excellenceService.selectExcellenceDetailList(map).get(0));
        return prefix + "/excellenceDetailEdit";
    }

    /**
     * 详情页面 编辑保存
     * <p>
     * Tip  分两种情况
     * 编辑图片:之前需要删除图片,已经进行了物理删除,这里直接上传
     * 不编辑图片:直接上传
     */
    @PostMapping("/updateExcellenceDetail")
    @ResponseBody
    public AjaxResult updateDanDetail(@RequestParam("file") MultipartFile file, ExcellenctDetail excellenctDetail) {
        try {

            // Step1 物理上传
            String fileName = FileUploadUtils.upload(Global.getUploadPath(), file);

            // Step1.2 准备参数
            excellenctDetail.setPhysicalPath(getPhysicalPath(Global.getUploadPath(), fileName));
            excellenctDetail.setFileName(fileName);
            excellenctDetail.setFilePath(ServerConfig.getUrl() + fileName);

            // Step2 更新响应
            return toAjax(excellenceService.updateExcellenceDetailById(excellenctDetail));
        } catch (Exception e) {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 编辑删除附件
     */
    @RequestMapping("/detailEditView/deletePic")
    @ResponseBody
    public AjaxResult detail(ExcellenctDetail excellenctDetail) {

        // Step1 根据ID进行物理删除
        Boolean flag = excellenceService.deleteFilePathById(Long.valueOf(excellenctDetail.getKey()));

        // Setp2 更新数据库响应
        if (flag) {
            return AjaxResult.success(excellenceService.updatePathById(Long.valueOf(String.valueOf(excellenctDetail.getKey()))));
        }
        return AjaxResult.error("失败");
    }
}
